package login;

import MSSQL.DBInitialize;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import javax.servlet.http.HttpSession;

public class loginaction extends ActionSupport {

    String username;
    String password;
    String identity;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getIdentity() {
        return identity;
    }

    public void setIdentity(String identity) {
        this.identity = identity;
    }

    @Override
    public String execute() throws Exception {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        Connection con
                = DriverManager.getConnection("jdbc:sqlserver://114.32.112.40:168;databasename=NorthWind", "leagueofpg", "gjun");
        Statement st = con.createStatement();
        String sql = "Select 員工編號 ,姓名 from 員工 where 員工編號=" + password;
        ResultSet rs;
        try {
            rs = st.executeQuery(sql);
            rs.next();
        } catch (Exception e) {
            System.out.println("密碼未輸入");
            addActionError("密碼未輸入");          
            return "error";
        }

        int count = rs.getRow();
        if (count == 0) {
            System.out.println("帳號不存在");
            addActionError("帳號不存在");
            return "error";
        } else {
            System.out.println("帳號存在");
        }
        ActionContext actionContext = ActionContext.getContext();
        Map session = actionContext.getSession();
        String str = (String) session.get("randonString");
        String name = rs.getString("姓名");
        String pwd = rs.getString("員工編號");
        if (username.equals(name) && password.equals(pwd)) {
            if (identity.equals(str)) {
                System.out.println("驗證碼成功");
                session.put("username", username);
                session.put("password", password);
                actionContext.setSession(session);
                return "success";
            } else {
                System.out.println("驗證碼失敗");
                addActionError("驗證碼錯誤");
                return "error";
            }
        } else {
            System.out.println("帳號密碼錯誤");
            addActionError("帳號密碼錯誤");
            return "error";
        }

    }

    public String identity() throws Exception {
        return "success";
    }

}
